package com.roc.web.action.terminal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosBatch;
import com.roc.service.IMerchantServices;
import com.roc.service.ITerminalSnBatchSerice;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/terminalSnBatch")
public class TerminalSnBatchQueryAction extends PaginationBaseAction  {

	static Logger logger = LogManager.getLogger(TerminalSnBatchQueryAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	private TerminalSnBatchQuerySearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();
	
	private String  batchNo; // 批次号(日期 + _ + 随机数)
	
	@Autowired
	IPageService pagenitionService;

	@Autowired
	private IorgService orgService;
	
	@Autowired 
	IMerchantServices merchantServices;

	@Autowired 
	ITerminalSnBatchSerice terminalSnBatchSericeImpl;

	@Action(value = "termSNBatchInit", results = { @Result(location = "/pages/terminal/termSnBatchList.jsp") })
	public String termSNBatchInit() throws Exception {

		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		String loginId = String.valueOf(logingOperators.getId());
		
		if( !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())  
				&& ! loginId.equals(Constant.SHOUDANSHIYEBU_ID)
				&& ! logingOperators.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();
		searchCondition = new TerminalSnBatchQuerySearchCondition();
		return SUCCESS;
	}

	@Action(value = "queryTerminalSNBatch", results = { @Result(name = "success", location = "/pages/terminal/termSnBatchList.jsp") })
	// 查询终端
	public String queryTerminalSNBatch() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (TerminalSnBatchQuerySearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new TerminalSnBatchQuerySearchCondition();
			}
		}
		try {
			String loginId = String.valueOf(op.getId());
			
			if( !op.getRoleType().equals(Role.SYSTEM.getCode())  
					&& ! loginId.equals(Constant.SHOUDANSHIYEBU_ID)
					&& ! op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();
/*
			String agentId = String.valueOf(op.getId());
			
			// 登录账号为管理员或仓库时
			if(op.getRoleType().equals(Role.SYSTEM.getCode())
					|| op.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode())) {
				agentId = Constant.SHOUDANSHIYEBU_ID;
			}
			
			searchCondition.setObj(agentId);
*/
			int rows = pagenitionService.countSQL(searchCondition);

			searchRsList = pagenitionService.findAllSQL(searchCondition,
					calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);

			List<YjPosBatch> posList = new ArrayList<YjPosBatch>();
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					YjPosBatch batchBean = new YjPosBatch();
					
					batchBean.setBatchNo(Constance.Null2EmptyTrim(obj[0])); // 批次号(日期 + _ + 随机数)
					batchBean.setBeginSerialNum(Constance.Null2EmptyTrim(obj[1])); // 开始sn字段
					batchBean.setEndSerialNum(Constance.Null2EmptyTrim(obj[2])); // 结束sn字段
					batchBean.setNums(Integer.parseInt(Constance.Null2EmptyTrim(obj[3]))); // 总数量
					batchBean.setRemark(Constance.Null2EmptyTrim(obj[4])); // 备注
					batchBean.setOrgCode(Constance.Null2EmptyTrim(obj[5])); // 机构代码
					batchBean.setOperatorNo(Constance.Null2EmptyTrim(obj[6])); // 操作账号
			//		batchBean.setOperatorId(Long.valueOf(Constance.Null2EmptyTrim(obj[7]))); // 操作id
			//		batchBean.setAgentId(Long.valueOf(Constance.Null2EmptyTrim(obj[8]))); // 代理商id
					batchBean.setDtCreateStr( Constance.Null2EmptyTrim(obj[9]) ); // 创建时间
					batchBean.setDtLastmodStr( Constance.Null2EmptyTrim(obj[10]) ); // 更新时间
					
					String brandCode = Constance.Null2EmptyTrim(obj[11]);
					batchBean.setPosBrand( ConfigMerinfoUtil.getPosBRAND(brandCode) ); // 厂商
					
					batchBean.setAgentName( Constance.Null2EmptyTrim(obj[12])); // 代理商名称
					
					posList.add(batchBean);
				}
			}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}

	
	@Action(value = "delTerminalSNBatch", 
			results = { @Result(name = "success",type="redirect", location = "/terminalSnBatch/queryTerminalSNBatch.ct" ),
			@Result(name = "error", location = "/error.jsp")
    })
    public String delTerminalSNBatch(){
		Operators logingOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		try{
			YjPosBatch posBatch = new YjPosBatch();
			posBatch.setBatchNo(batchNo);
			terminalSnBatchSericeImpl.deleteTerminalSNBatch(posBatch, logingOperators);
    	}catch(ServiceException e){
    		logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
    	}
		return SUCCESS;
    }

	private void org() {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		try {
			TblInsInf inf = new TblInsInf();
			orgList=orgService.listOrg(inf);

			// 查询所有一级代理商
		//	getRequest().setAttribute("oneAgentMap", getAllOneAgent());

			getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	protected void dealWithTheListSpecially(List<Object> list) {
		super.dealWithTheListSpecially(list);
		Map<String, String> roleTypes = ConfigProperties
				.getRoleTypeProperties();
		List<Object> tempList = new ArrayList<Object>();
		for (Object obj : list) {
			YjPosBatch pos = (YjPosBatch) obj;
			for (TblInsInf bean : orgList) {
				if (pos.getOrgCode().equals(bean.getInsIdCd())) {
					pos.setOrgName(bean.getInsName());
				}
			}

			tempList.add(pos);
		}
		searchRsList = tempList;
	}

	private Map<String, String> getAllOneAgent(){
		Map<String, String> map = new HashMap<String, String>();
		String sdsybId = Constant.SHOUDANSHIYEBU_ID;
		try {
			// 通过收单事业部 查询 各个区域信息
			List<Operators> areaList = merchantServices.queryLowOneAgent(sdsybId);
			for (Operators operators : areaList) {
				long areaId = operators.getId();
				List<Operators> oneAgentList = merchantServices.queryLowOneAgent(String.valueOf(areaId)); // 取一级代理商List
				for (Operators oBean : oneAgentList) {
					map.put(String.valueOf(oBean.getId()), oBean.getRealName());
				}
				
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError("查询一级代理商出现异常");
		}
		return map;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TerminalSnBatchQuerySearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TERM_SN_IMPORT);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERM_SN_IMPORT,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public TerminalSnBatchQuerySearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TerminalSnBatchQuerySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getBatchNo() {
		return batchNo;
	}

	public void setBatchNo(String batchNo) {
		this.batchNo = batchNo;
	}

}
